package edu.lingnan.lingnanblog.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import edu.lingnan.lingnanblog.entity.Blogger;
import edu.lingnan.lingnanblog.service.TBloggerService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * (TBlogger)表控制层
 *
 * @author makejava
 * @since 2020-06-13 08:34:08
 */
@RestController
@RequestMapping("blogger")
public class TBloggerController {
    /**
     * 服务对象
     */
    @Resource
    private TBloggerService tBloggerService;

    @PostMapping("login")
    public Blogger login(String name, String password){
        Blogger blogger = tBloggerService.login(name, password);
        if (blogger == null){
            return new Blogger();
        }else {
            return blogger;
        }
    }
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne/{id}")
    @HystrixCommand(fallbackMethod = "hystrixInstance") // 请求失败后调用备选方案：熔断
    public Blogger selectOne(@PathVariable("id") Integer id) {
        Blogger blogger = this.tBloggerService.queryById(id);
        if (blogger == null){
            throw new RuntimeException("用户不存在！");
        }
        return blogger;
    }


    @PostMapping("reg")
    @HystrixCommand(fallbackMethod = "hystrixReg")
    public boolean reg(@Valid Blogger bean) {
        return tBloggerService.insert(bean);
    }

    @GetMapping("getByName")
//    @HystrixCommand(fallbackMethod = "hystrixInstance")
    public Blogger getByName(String name){
        return tBloggerService.getByName(name);
    }

    @RequestMapping("/save")
//    @HystrixCommand(fallbackMethod = "hystrixReg")
    public boolean save( Blogger blogger){
        return tBloggerService.update(blogger);
    }


    // hystrix 的备选方案中，方法的参数类型，个数，和返回值必须对应

    public Blogger hystrixInstance(@PathVariable("id") Integer id){
        return new Blogger()
                .setId(id)
                .setName("该用户不存在！")
                .setSign("来自服务端的服务熔断~~~");
    }

    public boolean hystrixReg(Blogger bean){
        return false;
    }

}